// 文件: static/js/script.js

// --- 认证相关变量 ---
const authContainer = document.getElementById('authContainer');
const loginSection = document.getElementById('loginSection');
const registerSection = document.getElementById('registerSection');
const dashboardContainer = document.querySelector('.dashboard-container');

const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const showRegisterLink = document.getElementById('showRegister');
const showLoginLink = document.getElementById('showLogin');
const logoutBtn = document.getElementById('logoutBtn');

const loginErrorMsg = document.getElementById('loginError');
const registerErrorMsg = document.getElementById('registerError');
const currentUserDisplay = document.getElementById('currentUserDisplay');
const loginTimeDisplay = document.getElementById('loginTimeDisplay');

const USERS_STORAGE_KEY = 'smeRiskAppUsers';
const LOGGED_IN_USER_KEY = 'smeRiskAppLoggedInUser';

// --- 用户管理模态框相关变量 ---
const userManagementTrigger = document.getElementById('userManagementTrigger');
const userManagementModal = document.getElementById('userManagementModal');
const userManagementModalCloseBtn = document.getElementById('userManagementModalCloseBtn');
const userManagementErrorMsg = document.getElementById('userManagementError'); // Specific for user mgt modal
const userListContainer = document.getElementById('userListContainer');

// --- 风险参数配置模态框相关变量 ---
const riskParamsConfigTrigger = document.getElementById('riskParamsConfigTrigger');
const riskParamsModal = document.getElementById('riskParamsModal');
const riskParamsModalCloseBtnFromParams = document.getElementById('riskParamsModalCloseBtn'); // Ensure this ID is unique or handled
const riskParamsErrorMsg = document.getElementById('riskParamsError'); // Specific for risk params modal

const showManualInputBtn = document.getElementById('showManualInputBtn');
const showExcelUploadBtn = document.getElementById('showExcelUploadBtn');
const manualInputSection = document.getElementById('manualInputSection');
const excelUploadSection = document.getElementById('excelUploadSection');
const riskParamsForm = document.getElementById('riskParamsForm');
const uploadExcelBtn = document.getElementById('uploadExcelBtn');
const downloadExcelTemplateLink = document.getElementById('downloadExcelTemplate');

const customerChurnResultEl = document.getElementById('customerChurnResult');
const employeeTurnoverResultEl = document.getElementById('employeeTurnoverResult');

// --- 最近评估相关变量 ---
const recentAssessmentsTableBody = document.getElementById('recentAssessmentsTableBody');
let recentAssessments = []; // 存储最近评估记录的数组

// --- 系统统计相关变量 ---
const evaluatedCompaniesCountEl = document.getElementById('evaluatedCompaniesCount');
const highRiskCompaniesCountEl = document.getElementById('highRiskCompaniesCount');
const todayNewAssessmentsEl = document.getElementById('todayNewAssessments');


// --- 辅助函数 ---
function getStoredUsers() {
    const users = localStorage.getItem(USERS_STORAGE_KEY);
    return users ? JSON.parse(users) : [];
}

function storeUsers(users) {
    localStorage.setItem(USERS_STORAGE_KEY, JSON.stringify(users));
}

function displayLoginError(message) {
    if(loginErrorMsg) loginErrorMsg.textContent = message;
}

function displayRegisterError(message) {
    if(registerErrorMsg) registerErrorMsg.textContent = message;
}

function clearAuthErrors() {
    if(loginErrorMsg) loginErrorMsg.textContent = '';
    if(registerErrorMsg) registerErrorMsg.textContent = '';
}

// --- UI切换函数 ---
function showLoginFormView() {
    clearAuthErrors();
    if (authContainer) authContainer.style.display = 'flex';
    if (loginSection) loginSection.style.display = 'block';
    if (registerSection) registerSection.style.display = 'none';
    if (dashboardContainer) dashboardContainer.style.display = 'none';
}

function showRegisterFormView() {
    clearAuthErrors();
    if (authContainer) authContainer.style.display = 'flex';
    if (loginSection) loginSection.style.display = 'none';
    if (registerSection) registerSection.style.display = 'block';
    if (dashboardContainer) dashboardContainer.style.display = 'none';
}

// --- 认证逻辑 ---
function handleRegister(event) {
    event.preventDefault();
    clearAuthErrors();
    const phoneInput = document.getElementById('registerPhone');
    const emailInput = document.getElementById('registerEmail');
    const passwordInput = document.getElementById('registerPassword');
    const confirmPasswordInput = document.getElementById('registerConfirmPassword');

    if (!phoneInput || !emailInput || !passwordInput || !confirmPasswordInput) {
        displayRegisterError('表单字段获取失败。'); return;
    }
    const phone = phoneInput.value.trim();
    const email = emailInput.value.trim().toLowerCase();
    const password = passwordInput.value;
    const confirmPassword = confirmPasswordInput.value;

    if (!phone || !email || !password || !confirmPassword) { displayRegisterError('所有字段均为必填项。'); return; }
    if (!/^\d{11}$/.test(phone)) { displayRegisterError('请输入有效的11位手机号码。'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { displayRegisterError('请输入有效的邮箱地址。'); return; }
    if (password.length < 6) { displayRegisterError('密码至少需要6位。'); return; }
    if (password !== confirmPassword) { displayRegisterError('两次输入的密码不匹配。'); return; }

    const users = getStoredUsers();
    if (users.some(user => user.email === email)) { displayRegisterError('该邮箱已被注册。'); return; }
    if (users.some(user => user.phone === phone)) { displayRegisterError('该手机号已被注册。'); return; }

    users.push({ phone, email, password }); storeUsers(users);
    alert('注册成功！现在您可以登录了。');
    if(registerForm) registerForm.reset();
    showLoginFormView();
}

function handleLogin(event) {
    event.preventDefault();
    clearAuthErrors();
    const identifierInput = document.getElementById('loginIdentifier');
    const passwordInput = document.getElementById('loginPassword');

    if (!identifierInput || !passwordInput) { displayLoginError('表单字段获取失败。'); return; }
    const identifier = identifierInput.value.trim().toLowerCase();
    const password = passwordInput.value;

    if (!identifier || !password) { displayLoginError('请输入邮箱/手机号和密码。'); return; }

    const users = getStoredUsers();
    const foundUser = users.find(user => (user.email === identifier || user.phone === identifier) && user.password === password);

    if (foundUser) {
        localStorage.setItem(LOGGED_IN_USER_KEY, JSON.stringify({ identifier: foundUser.email, loginTime: new Date().toISOString() }));
        if(loginForm) loginForm.reset();
        showDashboardView(foundUser.email);
    } else {
        displayLoginError('邮箱/手机号或密码错误。');
    }
}

function handleLogout() {
    localStorage.removeItem(LOGGED_IN_USER_KEY);
    if (currentUserDisplay) currentUserDisplay.textContent = '未登录';
    if (loginTimeDisplay) loginTimeDisplay.textContent = 'N/A';
    dashboardComponentsInitialized = false; // Reset initialization flag
    recentAssessments = []; // Clear recent assessments on logout
    updateRecentAssessmentsTable(); // Clear the table display
    updateSystemStats(); // Reset stats display
    showLoginFormView();
}

function checkInitialAuthState() {
    const loggedInUserStr = localStorage.getItem(LOGGED_IN_USER_KEY);
    if (loggedInUserStr) {
        try {
            const loggedInUser = JSON.parse(loggedInUserStr);
            showDashboardView(loggedInUser.identifier);
        } catch (e) {
            localStorage.removeItem(LOGGED_IN_USER_KEY); showLoginFormView();
        }
    } else {
        showLoginFormView();
    }
}

// --- 用户管理功能 ---
function displayUserManagementError(message) {
    if (userManagementErrorMsg) userManagementErrorMsg.textContent = message;
}

function openUserManagementModal() {
    if (!userManagementModal || !userListContainer) return;
    displayUserManagementError('');
    userListContainer.innerHTML = '<p>正在加载用户数据...</p>';
    const users = getStoredUsers();
    if (users.length === 0) {
        userListContainer.innerHTML = '<p>目前还没有注册用户。</p>';
    } else {
        let userListHTML = users.map((user, index) => {
            const identifier = user.email || user.phone;
            const isAdmin = index === 0; // Assuming the first registered user is admin
            return `
                <div class="user-list-item">
                    <span class="user-identifier">${identifier}</span>
                    ${isAdmin ? '<span class="user-role">(管理员)</span>' : ''}
                </div>
            `;
        }).join('');
        userListContainer.innerHTML = userListHTML;
    }
    userManagementModal.style.display = 'block';
}

function closeUserManagementModal() {
    if (userManagementModal) userManagementModal.style.display = 'none';
}

// --- 风险参数配置功能 ---
function displayRiskConfigError(message) { // Renamed to avoid conflict
    if (riskParamsErrorMsg) riskParamsErrorMsg.textContent = message;
}

function clearRiskParamsFormAndResults() {
    if(riskParamsForm) riskParamsForm.reset();
    if(customerChurnResultEl) customerChurnResultEl.textContent = '--';
    if(employeeTurnoverResultEl) employeeTurnoverResultEl.textContent = '--';
    if(riskParamsErrorMsg) riskParamsErrorMsg.textContent = '';
    const excelFile = document.getElementById('excelFile');
    if(excelFile) excelFile.value = '';
}

function openRiskParamsModal() {
    if (!riskParamsModal) return;
    clearRiskParamsFormAndResults();
    if(manualInputSection) manualInputSection.style.display = 'block';
    if(excelUploadSection) excelUploadSection.style.display = 'none';
    if(showManualInputBtn) showManualInputBtn.classList.add('active-tab');
    if(showExcelUploadBtn) showExcelUploadBtn.classList.remove('active-tab');
    riskParamsModal.style.display = 'block';
}

function closeRiskParamsModal() {
    if (riskParamsModal) riskParamsModal.style.display = 'none';
}

function calculateRates(event) {
    if(event) event.preventDefault();
    displayRiskConfigError(''); // Use renamed error display function

    const custInitial = parseFloat(document.getElementById('custInitialCount').value);
    const custEnd = parseFloat(document.getElementById('custEndCount').value);
    const custLost = parseFloat(document.getElementById('custLostCount').value);
    let customerChurnRate = NaN;
    if (!isNaN(custLost) && !isNaN(custInitial) && custInitial > 0) {
        customerChurnRate = (custLost / custInitial) * 100;
    } else if (!isNaN(custLost) && !isNaN(custInitial) && !isNaN(custEnd) && (custInitial + custEnd) > 0) {
        customerChurnRate = (custLost / ((custInitial + custEnd) / 2)) * 100;
    }

    const empInitial = parseFloat(document.getElementById('empInitialCount').value);
    const empEnd = parseFloat(document.getElementById('empEndCount').value);
    const empLeft = parseFloat(document.getElementById('empLeftCount').value);
    let employeeTurnoverRate = NaN;
    if (!isNaN(empLeft) && !isNaN(empInitial) && empInitial > 0) {
        employeeTurnoverRate = (empLeft / empInitial) * 100;
    } else if (!isNaN(empLeft) && !isNaN(empInitial) && !isNaN(empEnd) && (empInitial + empEnd) > 0) {
        employeeTurnoverRate = (empLeft / ((empInitial + empEnd) / 2)) * 100;
    }

    if (customerChurnResultEl) customerChurnResultEl.textContent = isNaN(customerChurnRate) ? '无法计算' : customerChurnRate.toFixed(2);
    if (employeeTurnoverResultEl) employeeTurnoverResultEl.textContent = isNaN(employeeTurnoverRate) ? '无法计算' : employeeTurnoverRate.toFixed(2);

    let errorMessages = [];
    if (isNaN(custLost) || (isNaN(custInitial) && isNaN(custEnd))) errorMessages.push('客户流失率计算需要流失客户数和期初/期末客户数。');
    if (isNaN(empLeft) || (isNaN(empInitial) && isNaN(empEnd))) errorMessages.push('员工流动率计算需要离职员工数和期初/期末员工数。');

    if (errorMessages.length > 0) displayRiskConfigError(errorMessages.join(' '));
    else displayRiskConfigError(''); // Clear error if calculation is successful
}

async function handleExcelUploadAndProcess() {
    const excelFileElement = document.getElementById('excelFile');
    displayRiskConfigError(''); // Use renamed error display function

    if (!excelFileElement || !excelFileElement.files || excelFileElement.files.length === 0) {
        displayRiskConfigError('请先选择一个Excel文件。');
        return;
    }

    if (typeof XLSX === 'undefined') {
        displayRiskConfigError("Excel处理库未加载，无法解析文件。请检查网络连接。");
        console.error("XLSX (SheetJS) library is not loaded.");
        return;
    }

    const file = excelFileElement.files[0];
    const fileName = file.name;
    const originalUploadBtnText = uploadExcelBtn ? uploadExcelBtn.innerHTML : '';
    if (uploadExcelBtn) {
        uploadExcelBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        uploadExcelBtn.disabled = true;
    }

    try {
        const data = await file.arrayBuffer();
        const workbook = XLSX.read(data);

        const sheetName = "输入数据";
        const worksheet = workbook.Sheets[sheetName];

        if (!worksheet) {
            throw new Error(`Excel文件中未找到名为 "${sheetName}" 的工作表。请参照模板。`);
        }

        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        const findValueByLabel = (dataArray, label) => {
            for (const row of dataArray) {
                if (row && row[0] && typeof row[0] === 'string' && row[0].trim() === label.trim()) {
                    if (row.length > 1 && (typeof row[1] === 'number' || (typeof row[1] === 'string' && row[1].trim() !== ''))) {
                        const parsedVal = parseFloat(row[1]);
                        // Return number if it's a valid number, otherwise return the string value
                        return !isNaN(parsedVal) && String(parsedVal) === String(row[1]).trim() ? parsedVal : (typeof row[1] === 'string' ? row[1].trim() : row[1]);
                    }
                    return null; // Label found, but no value in column B
                }
            }
            return undefined; // Label not found
        };


        fillInput('custInitialCount', findValueByLabel(jsonData, "期初客户总数"));
        fillInput('custEndCount', findValueByLabel(jsonData, "期末客户总数"));
        fillInput('custNewCount', findValueByLabel(jsonData, "期间新增客户数"));
        fillInput('custLostCount', findValueByLabel(jsonData, "期间流失客户数"));
        fillInput('custCategory', findValueByLabel(jsonData, "客户分类信息"));
        fillInput('custChurnReason', findValueByLabel(jsonData, "流失原因分类"));
        fillInput('custLifecycle', findValueByLabel(jsonData, "客户生命周期"));
        fillInput('custValue', findValueByLabel(jsonData, "客户价值信息"));


        fillInput('empInitialCount', findValueByLabel(jsonData, "期初员工总数"));
        fillInput('empEndCount', findValueByLabel(jsonData, "期末员工总数"));
        fillInput('empHiredCount', findValueByLabel(jsonData, "期间新聘员工数"));
        fillInput('empLeftCount', findValueByLabel(jsonData, "期间离职员工数"));
        fillInput('empCategory', findValueByLabel(jsonData, "员工分类信息"));
        fillInput('empLeaveType', findValueByLabel(jsonData, "离职类型"));
        fillInput('empTenure', findValueByLabel(jsonData, "员工在职时间"));
        fillInput('empKeyPosition', findValueByLabel(jsonData, "关键岗位标识"));
        fillInput('empLeaveReason', findValueByLabel(jsonData, "离职原因分类"));


        const custLostVal = parseFloat(document.getElementById('custLostCount').value);
        const custInitialVal = parseFloat(document.getElementById('custInitialCount').value);
        const custEndVal = parseFloat(document.getElementById('custEndCount').value);
        const empLeftVal = parseFloat(document.getElementById('empLeftCount').value);
        const empInitialVal = parseFloat(document.getElementById('empInitialCount').value);
        const empEndVal = parseFloat(document.getElementById('empEndCount').value);

        if (isNaN(custLostVal) || isNaN(empLeftVal) || (isNaN(custInitialVal) && isNaN(custEndVal)) || (isNaN(empInitialVal) && isNaN(empEndVal)) ) {
             throw new Error("Excel 文件中缺少计算所需的关键数值 (如流失/离职数、期初/期末数)，或数值格式不正确。请参照模板。");
        }

        calculateRates();
        alert(`文件 "${fileName}" 中的数据已成功读取并用于计算比率。`);

    } catch (error) {
        console.error("处理Excel文件时出错:", error);
        displayRiskConfigError(`处理文件失败: ${error.message}`);
        if(customerChurnResultEl) customerChurnResultEl.textContent = '--';
        if(employeeTurnoverResultEl) employeeTurnoverResultEl.textContent = '--';
    } finally {
        if (uploadExcelBtn) {
            uploadExcelBtn.innerHTML = originalUploadBtnText || '<i class="fas fa-upload"></i> 上传并处理';
            uploadExcelBtn.disabled = false;
        }
    }
}

function fillInput(id, value) {
    const el = document.getElementById(id);
    if (el) {
        // Only set value if it's not undefined or null
        if (value !== undefined && value !== null) {
             // For select elements, ensure the option exists before setting
            if (el.tagName === 'SELECT') {
                const optionExists = Array.from(el.options).some(option => option.value === String(value));
                if (optionExists) {
                     el.value = String(value);
                } else {
                    console.warn(`Select element with ID ${id} does not have an option with value "${value}". Skipping.`);
                     // Optionally set to default or leave as is
                }
            } else {
                 el.value = value;
            }
        }
        // else { el.value = ''; } // Optionally clear if not found
    }
}


function generateAndDownloadExcelTemplate() {
    if (typeof XLSX === 'undefined') {
        alert("Excel导出库 (SheetJS) 未加载。"); console.error("XLSX (SheetJS) library not loaded."); return;
    }
    const wb = XLSX.utils.book_new();
    const dataSheetContent = [
        ["标签 (A列)", "数值/说明 (B列)"], ["", ""],
        ["客户流失率相关数据", ""], ["期初客户总数", null], ["期末客户总数", null], ["期间新增客户数", null], ["期间流失客户数", null],
        ["客户分类信息", "示例: VIP, 普通"], ["流失原因分类", "示例: 自愿, 价格"], ["客户生命周期", "示例: 新客户, 成长客户, 成熟客户"], ["客户价值信息", "示例: 高价值, 中价值"], ["", ""],
        ["员工流动率相关数据", ""], ["期初员工总数", null], ["期末员工总数", null], ["期间新聘员工数", null], ["期间离职员工数", null],
        ["员工分类信息", "示例: 管理, 技术"], ["离职类型", "示例: 自愿, 裁员"], ["员工在职时间", "示例: <1年, 1-3年"], ["关键岗位标识", "示例: 是, 否"], ["离职原因分类", "示例: 薪资, 发展"]
    ];
    const ws = XLSX.utils.aoa_to_sheet(dataSheetContent);
    ws['!cols'] = [ {wch:30}, {wch:30} ];
    XLSX.utils.book_append_sheet(wb, ws, "输入数据");
    XLSX.writeFile(wb, "风险参数输入模板.xlsx");
}

// --- 初始化全局图表变量等 ---
let radarChart; let riskDistributionChart; let amapInstance; let markerClusterer; let allAmapMarkers = [];
let dashboardComponentsInitialized = false;
const companies = [
    { name: "涧石科技有限公司", lat: 39.9042, lng: 116.4074, city: "北京", risk: "high", description: "供应链风险较高" },
    { name: "云岫商贸有限公司", lat: 31.2304, lng: 121.4737, city: "上海", risk: "medium", description: "财务状况一般" },
    { name: "磐石基建有限公司", lat: 23.1291, lng: 113.2644, city: "广州", risk: "low", description: "财务健康状况良好" },
];
const colorMapping = { high: '#ff3366', medium: '#ffcc00', low: '#33cc33' };

// --- 仪表盘组件初始化及相关函数 ---
function initRadarChart() {
    const radarChartDom = document.getElementById('radarChart');
    if (!radarChartDom) return;
    if (echarts.getInstanceByDom(radarChartDom)) echarts.getInstanceByDom(radarChartDom).dispose();
    radarChart = echarts.init(radarChartDom);
    const option = {
        title: { text: '风险维度分析', left: 'center', textStyle: { color: '#e0f0ff' } },
        tooltip: { trigger: 'item' },
        radar: {
            indicator: [ { name: '财务风险', max: 100 }, { name: '市场风险', max: 100 }, { name: '管理风险', max: 100 }, { name: '外部风险', max: 100 } ],
            axisName: { color: '#e0f0ff', fontSize: 12 },
            splitLine: { lineStyle: { color: 'rgba(224, 240, 255, 0.3)' } },
            splitArea: { areaStyle: { color: ['rgba(77, 171, 255, 0.1)', 'rgba(77, 171, 255, 0.05)'] } },
            axisLine: { lineStyle: { color: 'rgba(224, 240, 255, 0.5)' } }
        },
        series: [{
            name: '风险评估结果', type: 'radar', data: [{ value: [0, 0, 0, 0], name: '本次评估' }],
            symbol: 'circle', symbolSize: 6, lineStyle: { color: '#00c3ff', width: 2 },
            areaStyle: { opacity: 0.6, color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [{ offset: 0, color: 'rgba(0, 195, 255, 0.1)' },{ offset: 1, color: 'rgba(0, 195, 255, 0.6)' }])},
            itemStyle: { color: '#00c3ff' }, label: { show: true, formatter: '{c}', color: '#fff', fontSize: 10 }
        }]
    };
    radarChart.setOption(option);
    if (dashboardContainer && dashboardContainer.style.display !== 'none') radarChart.resize();
}

function updateRiskLevel(score) {
    const riskLevelElement = document.getElementById('riskLevel');
    const riskScoreElement = document.getElementById('riskScore');
    if (!riskLevelElement || !riskScoreElement) return;
    if (score === '--' || score === null || typeof score === 'undefined') {
        riskLevelElement.textContent = '--'; riskLevelElement.className = 'risk-level';
        riskScoreElement.textContent = '--'; riskScoreElement.className = 'risk-score';
        return;
    }
    const numericScore = Number(score);
    if (isNaN(numericScore)) { updateRiskLevel('--'); return; }
    riskScoreElement.textContent = numericScore;
    if (numericScore >= 70) {
        riskLevelElement.textContent = '高风险'; riskLevelElement.className = 'risk-level level-high';
        riskScoreElement.className = 'risk-score risk-high';
    } else if (numericScore >= 40) {
        riskLevelElement.textContent = '中风险'; riskLevelElement.className = 'risk-level level-medium';
        riskScoreElement.className = 'risk-score risk-medium';
    } else {
        riskLevelElement.textContent = '低风险'; riskLevelElement.className = 'risk-level level-low';
        riskScoreElement.className = 'risk-score risk-low';
    }
}

// --- 新增函数：更新最近评估表格 ---
function updateRecentAssessmentsTable() {
    if (!recentAssessmentsTableBody) return;

    if (recentAssessments.length === 0) {
        recentAssessmentsTableBody.innerHTML = '<tr><td colspan="3" style="text-align:center;">暂无评估记录</td></tr>';
        return;
    }

    let tableHTML = '';
    recentAssessments.forEach(assessment => {
        let riskColor = '';
        if (assessment.riskLevel === '高风险') riskColor = 'var(--danger-color)';
        else if (assessment.riskLevel === '中风险') riskColor = 'var(--warning-color)';
        else riskColor = 'var(--success-color)';

        tableHTML += `
            <tr>
                <td>${assessment.name}</td>
                <td><span style="color: ${riskColor};">${assessment.riskLevel}</span></td>
                <td>${assessment.time}</td>
            </tr>
        `;
    });

    recentAssessmentsTableBody.innerHTML = tableHTML;
    updateSystemStats(); // Update stats whenever the table is updated
}

// --- 新增函数：获取后端最近评估记录 ---
async function fetchRecentAssessments() {
    try {
        const response = await fetch('/api/recent_assessments');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        if (result.success) {
            recentAssessments = result.assessments; // Update the frontend array
            updateRecentAssessmentsTable(); // Update the table display
        } else {
            console.error('Failed to fetch recent assessments:', result.error);
            if (recentAssessmentsTableBody) {
                 recentAssessmentsTableBody.innerHTML = '<tr><td colspan="3" style="text-align:center; color: var(--danger-color);">加载评估记录失败</td></tr>';
            }
        }
    } catch (error) {
        console.error('Error fetching recent assessments:', error);
         if (recentAssessmentsTableBody) {
             recentAssessmentsTableBody.innerHTML = `<tr><td colspan="3" style="text-align:center; color: var(--danger-color);">加载评估记录出错: ${error.message}</td></tr>`;
         }
    }
}

// --- 新增函数：更新系统统计 ---
function updateSystemStats() {
    if (!evaluatedCompaniesCountEl || !highRiskCompaniesCountEl || !todayNewAssessmentsEl) return;

    const totalCount = recentAssessments.length;
    const highRiskCount = recentAssessments.filter(a => a.riskLevel === '高风险').length;

    // Calculate today's assessments (simple check based on date string)
    const today = new Date().toISOString().split('T')[0];
    const todayCount = recentAssessments.filter(a => a.time && a.time.startsWith(today)).length;


    evaluatedCompaniesCountEl.textContent = totalCount;
    highRiskCompaniesCountEl.textContent = highRiskCount;
    todayNewAssessmentsEl.textContent = todayCount;

    // Update Pie Chart data (assuming it represents the distribution of recent assessments)
    if (riskDistributionChart) {
        const lowRiskCount = recentAssessments.filter(a => a.riskLevel === '低风险').length;
        const mediumRiskCount = recentAssessments.filter(a => a.riskLevel === '中风险').length;
        const highRiskCountForChart = recentAssessments.filter(a => a.riskLevel === '高风险').length; // Recalculate for clarity

        riskDistributionChart.data.datasets[0].data = [lowRiskCount, mediumRiskCount, highRiskCountForChart];
        riskDistributionChart.update();
    }
}


const analyzeBtn = document.getElementById('analyzeBtn');
if (analyzeBtn) {
    analyzeBtn.addEventListener('click', function() {
        const companyNameInput = document.getElementById('companyName');
        const companyName = companyNameInput ? companyNameInput.value.trim() : '';

        const data = {
            companyName: companyName || '未命名企业', // Use input name or default
            revenue: document.getElementById('revenue').value,
            profitMargin: document.getElementById('profitMargin').value,
            debtRatio: document.getElementById('debtRatio').value,
            cashFlow: document.getElementById('cashFlow').value,
            marketShare: document.getElementById('marketShare').value,
            competitors: document.getElementById('competitors').value,
            customerChurn: document.getElementById('customerChurn').value,
            employeeTurnover: document.getElementById('employeeTurnover').value,
            managementStability: document.getElementById('managementStability').value,
            innovationAbility: document.getElementById('innovationAbility').value,
            industryRisk: document.getElementById('industryRisk').value,
            policySupport: document.getElementById('policySupport').value
        };

        const originalBtnText = analyzeBtn.innerHTML; analyzeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 评估中...'; analyzeBtn.disabled = true;
        document.getElementById('riskFactors').innerHTML = '<p>正在生成风险因素...</p>'; document.getElementById('suggestions').innerHTML = '<p>正在生成改进建议...</p>';
        updateRiskLevel('--'); if (radarChart) radarChart.setOption({ series: [{ data: [{ value: [0, 0, 0, 0] }] }] });

        fetch('/api/analyze_risk', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
        .then(response => { if (!response.ok) { return response.json().then(errData => { throw new Error(errData.error || response.statusText || `HTTP error! status: ${response.status}`); }).catch(() => { throw new Error(`HTTP error! status: ${response.status}`); }); } return response.json(); })
        .then(result => {
            analyzeBtn.innerHTML = originalBtnText; analyzeBtn.disabled = false;
            if (result.success) {
                updateRiskLevel(result.totalRisk);
                if (!radarChart && document.getElementById('radarChart')) initRadarChart();
                if (radarChart) { radarChart.setOption({ series: [{ data: [{ value: [result.financialRisk || 0, result.marketRisk || 0, result.managementRisk || 0, result.externalRisk || 0], name: '本次评估' }] }] }); if (dashboardContainer && dashboardContainer.style.display !== 'none') radarChart.resize(); }
                document.getElementById('riskFactors').innerHTML = result.riskFactorsHtml || '<p>未提供风险因素。</p>'; document.getElementById('suggestions').innerHTML = result.suggestionsHtml || '<p>未提供改进建议。</p>';

                // --- 评估成功后，更新前端的最近评估列表并刷新表格 ---
                // Note: The backend already added the new assessment to its list.
                // We refetch the list from the backend to ensure consistency,
                // especially if multiple users were assessing simultaneously (though this simple app doesn't handle that).
                // For a single-user in-memory approach, you could also just add the new assessment to the frontend 'recentAssessments' array directly.
                fetchRecentAssessments(); // Fetch and update the table
                // --------------------------------------------------

            } else {
                document.getElementById('riskFactors').innerHTML = `<p class="error-message">风险分析失败: ${result.error || '未知错误'}</p>`;
                document.getElementById('suggestions').innerHTML = '<p>未能生成改进建议。</p>';
                updateRiskLevel('--');
                if (radarChart) radarChart.setOption({ series: [{ data: [{ value: [0,0,0,0] }] }] });
            }
        })
        .catch(error => {
            analyzeBtn.innerHTML = originalBtnText; analyzeBtn.disabled = false;
            document.getElementById('riskFactors').innerHTML = `<p class="error-message">请求出错: ${error.message}。</p>`;
            document.getElementById('suggestions').innerHTML = '<p>未能生成改进建议。</p>';
            updateRiskLevel('--');
            if (radarChart) radarChart.setOption({ series: [{ data: [{ value: [0,0,0,0] }] }] });
        });
    });
}


function initAMap() {
    const mapElement = document.getElementById('map'); if (!mapElement) return;
    if (typeof AMap === "undefined") { mapElement.innerHTML = "<p style='text-align:center; padding: 20px; color: red;'>高德地图加载失败</p>"; return; }
    amapInstance = new AMap.Map(mapElement, { resizeEnable: true, zoom: 5, center: [108.948021, 34.263161], viewMode: '2D' });
    AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.MarkerClusterer'], function() {
        amapInstance.addControl(new AMap.ToolBar()); amapInstance.addControl(new AMap.Scale()); amapInstance.addControl(new AMap.HawkEye({ isOpen: false })); amapInstance.addControl(new AMap.MapType());
        markerClusterer = new AMap.MarkerClusterer(amapInstance, [], { gridSize: 60, maxZoom: 15 }); createAndAddMarkers();
    });
}

function createAndAddMarkers(filteredCompanies = companies) {
    if (!amapInstance) return; allAmapMarkers = []; const markersToAdd = [];
    if (markerClusterer) markerClusterer.clearMarkers(); else amapInstance.clearMap();
    filteredCompanies.forEach(company => {
        const markerPosition = new AMap.LngLat(company.lng, company.lat);
        const markerContent = `<div class="custom-amap-marker"><div style="background-color:${colorMapping[company.risk]};" class="marker-pin-amap"></div><i class="fas fa-building marker-icon-amap"></i></div>`;
        const amapMarker = new AMap.Marker({ position: markerPosition, content: markerContent, offset: new AMap.Pixel(-15, -42), extData: company });
        const infoWindowContent = `<div class="amap-info-window"><h4>${company.name}</h4><p>城市: ${company.city}</p><p>风险等级: <span style="color:${colorMapping[company.risk]}; font-weight:bold;">${company.risk === 'high' ? '高风险' : company.risk === 'medium' ? '中风险' : '低风险'}</span></p><p>简述: ${company.description}</p></div>`;
        const infoWindow = new AMap.InfoWindow({ content: infoWindowContent, offset: new AMap.Pixel(0, -30) });
        amapMarker.on('click', function() { infoWindow.open(amapInstance, amapMarker.getPosition()); });
        allAmapMarkers.push(amapMarker); markersToAdd.push(amapMarker);
    });
    if (markerClusterer) markerClusterer.addMarkers(markersToAdd); else amapInstance.add(markersToAdd);
    if (markersToAdd.length > 0 && dashboardContainer && dashboardContainer.style.display !== 'none') { amapInstance.setFitView(markersToAdd, false, [60, 60, 60, 60], 16); }
    else if (filteredCompanies.length === 0 && dashboardContainer && dashboardContainer.style.display !== 'none' && document.getElementById('searchInput')?.value.trim() !== "") {}
    else if (filteredCompanies.length === 0 && dashboardContainer && dashboardContainer.style.display !== 'none') { amapInstance.setZoomAndCenter(5, [108.948021, 34.263161]); }
}

function initDashboardComponents() {
    if (dashboardComponentsInitialized) return;
    if (document.getElementById('map')) initAMap();
    const pieChartCanvas = document.getElementById('riskDistributionChart');
    if (pieChartCanvas) {
        if (riskDistributionChart) riskDistributionChart.destroy();
        // Initial data for the pie chart can be based on the fetched recent assessments
        const lowRiskCount = recentAssessments.filter(a => a.riskLevel === '低风险').length;
        const mediumRiskCount = recentAssessments.filter(a => a.riskLevel === '中风险').length;
        const highRiskCount = recentAssessments.filter(a => a.riskLevel === '高风险').length;

        riskDistributionChart = new Chart(pieChartCanvas.getContext('2d'), { type: 'doughnut', data: { labels: ['低风险', '中风险', '高风险'], datasets: [{ data: [lowRiskCount, mediumRiskCount, highRiskCount], backgroundColor: [colorMapping.low + 'AA', colorMapping.medium + 'AA', colorMapping.high + 'AA'], borderColor: [colorMapping.low, colorMapping.medium, colorMapping.high], borderWidth: 1, hoverOffset: 4 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom', labels: { color: '#e0f0ff' } }, title: { display: true, text: '风险企业数量分布', color: '#e0f0ff', padding: { top: 10, bottom: 15 } }, tooltip: { callbacks: { label: function(c) { return (c.label||'') + (c.label?': ':'') + (c.parsed!==null ? c.parsed+' 家':''); } } } }, cutout: '60%' } });
    }
    if (document.getElementById('radarChart')) initRadarChart();
    dashboardComponentsInitialized = true;
}

async function showDashboardView(userEmailOrPhone) {
    if(authContainer) authContainer.style.display = 'none'; if(dashboardContainer) dashboardContainer.style.display = 'block';
    if(currentUserDisplay) currentUserDisplay.textContent = userEmailOrPhone; if(loginTimeDisplay) loginTimeDisplay.textContent = new Date().toLocaleString();

    // Fetch recent assessments before initializing dashboard components
    await fetchRecentAssessments();

    initDashboardComponents();

    setTimeout(() => {
        if (radarChart && typeof radarChart.resize === 'function' && !radarChart.isDisposed()) { try { radarChart.resize(); } catch(e) {} }
        // Also resize AMap if needed
        if (amapInstance && typeof amapInstance.checkSize === 'function') { try { amapInstance.checkSize(); } catch(e) {} }
    }, 150);
}

// --- DOMContentLoaded Event Listener (主执行逻辑) ---
document.addEventListener('DOMContentLoaded', function() {
    if(loginForm) loginForm.addEventListener('submit', handleLogin);
    if(registerForm) registerForm.addEventListener('submit', handleRegister);
    if(showRegisterLink) showRegisterLink.addEventListener('click', (e) => { e.preventDefault(); showRegisterFormView(); });
    if(showLoginLink) showLoginLink.addEventListener('click', (e) => { e.preventDefault(); showLoginFormView(); });
    if(logoutBtn) logoutBtn.addEventListener('click', handleLogout);

    if (userManagementTrigger) {
        userManagementTrigger.addEventListener('click', function(e) {
            e.preventDefault();
            if (dashboardContainer && dashboardContainer.style.display !== 'none') openUserManagementModal();
            else alert("请先登录系统。");
        });
    }
    if (userManagementModalCloseBtn) userManagementModalCloseBtn.addEventListener('click', closeUserManagementModal);
    if (userManagementModal) window.addEventListener('click', (event) => { if (event.target === userManagementModal) closeUserManagementModal(); });

    const actualRiskParamsModalCloseBtn = document.getElementById('riskParamsModalCloseBtn');
    if (riskParamsConfigTrigger) {
        riskParamsConfigTrigger.addEventListener('click', function(e) {
            e.preventDefault();
            if (dashboardContainer && dashboardContainer.style.display !== 'none') openRiskParamsModal();
            else alert("请先登录系统。");
        });
    }
    if (actualRiskParamsModalCloseBtn) {
        actualRiskParamsModalCloseBtn.addEventListener('click', closeRiskParamsModal);
    }
    if (riskParamsModal) window.addEventListener('click', (event) => { if (event.target === riskParamsModal) closeRiskParamsModal(); });

    if (showManualInputBtn && manualInputSection && excelUploadSection && showExcelUploadBtn) {
        showManualInputBtn.addEventListener('click', () => {
            manualInputSection.style.display = 'block'; excelUploadSection.style.display = 'none';
            showManualInputBtn.classList.add('active-tab'); showExcelUploadBtn.classList.remove('active-tab');
        });
        showExcelUploadBtn.addEventListener('click', () => {
            manualInputSection.style.display = 'none'; excelUploadSection.style.display = 'block';
            showExcelUploadBtn.classList.add('active-tab'); showManualInputBtn.classList.remove('active-tab');
            clearRiskParamsFormAndResults();
        });
    }
    if (riskParamsForm) riskParamsForm.addEventListener('submit', calculateRates);
    if (uploadExcelBtn) uploadExcelBtn.addEventListener('click', handleExcelUploadAndProcess);
    if (downloadExcelTemplateLink) downloadExcelTemplateLink.addEventListener('click', (e) => { e.preventDefault(); generateAndDownloadExcelTemplate(); });

    checkInitialAuthState();

    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            if (dashboardContainer && dashboardContainer.style.display === 'none') return;
            const searchTerm = this.value.toLowerCase().trim();
            let filteredResult = searchTerm === "" ? companies : companies.filter(c => c.name.toLowerCase().includes(searchTerm) || c.city.toLowerCase().includes(searchTerm));
            createAndAddMarkers(filteredResult);
        });
    }

    window.addEventListener('resize', function() {
        if (dashboardContainer && dashboardContainer.style.display === 'none') return;
        if (radarChart && !radarChart.isDisposed()) { try { radarChart.resize(); } catch (e) {} }
         if (amapInstance && typeof amapInstance.checkSize === 'function') { try { amapInstance.checkSize(); } catch(e) {} }
    });
});